#include "ccid_cmd.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

_ccid_cmd::_ccid_cmd(unsigned char *_data)
{
    memset(header, 0x0, 10);
    datalen = 0;
    data = _data;
}

_ccid_cmd::~_ccid_cmd()
{
    memset(header, 0x0, 10);
    datalen = 0;
}

void _ccid_cmd::setMessage(unsigned char message)
{
    header[0] = message;
}

void _ccid_cmd::setSqId(unsigned char _sqId)
{
    header[5] = _sqId;
}

unsigned char _ccid_cmd::getSqId()
{
    return header[5];
}

unsigned char _ccid_cmd::getStatus()
{
    return header[6];
}

void _ccid_cmd::setData(unsigned char *_data, int _dataLen)
{
    datalen = 0;
    unsigned char *pLenStart = &header[1];
    memset(pLenStart, 0x0, 4);
    if(NULL != _data && _dataLen > 0)
    {
        memcpy(data, _data, _dataLen);
        datalen = _dataLen;
        pLenStart[0] = (_dataLen & 0xFF);
        pLenStart[1] = ((_dataLen >> 8) & 0xFF);
        pLenStart[2] = ((_dataLen >> 16) & 0xFF);
        pLenStart[3] = ((_dataLen >> 24) & 0xFF);
    }
}

unsigned char *_ccid_cmd::getData()
{
    return data;
}

int _ccid_cmd::getDataLen()
{
    return datalen;
}

void _ccid_cmd::packet(unsigned char *pBuffer)
{
    int nOffset = 0;
    memcpy(pBuffer + nOffset, header, 10);
    nOffset += 10;
    if(NULL != data && datalen > 0)
    {
        memcpy(pBuffer + nOffset, data, datalen);
    }
}

int _ccid_cmd::unPacket(unsigned char *pBuffer, int cbBuffer)
{
    if(NULL == pBuffer || cbBuffer < 10)
    {
        return -1;
    }
    datalen = 0;
    int nOffset = 0;
    memcpy(header + nOffset, pBuffer, 10);
    nOffset += 10;
    int _tempLen = calcPacketLen(pBuffer, cbBuffer);
    if(_tempLen > 0)
    {
        memcpy(data, pBuffer + nOffset, _tempLen);
        datalen = _tempLen;
    }
    return 0;
}

int _ccid_cmd::calcPacketLen(unsigned char *pBuffer, int cbBuffer)
{
    if(NULL == pBuffer || cbBuffer < 10)
    {
        return -1;
    }
    unsigned char *pLenStart = &pBuffer[1];
    int len = (pLenStart[0] & 0xFF);
    len += ((pLenStart[1] << 8) & 0xFF00);
    len += ((pLenStart[2] << 16) & 0xFF0000);
    len += ((pLenStart[3] << 24) & 0xFF000000);
    if(len > 8 * 1024)
    {
        return -2;
    }
    return len;
}